<?php
declare (strict_types = 1);

namespace app\model;

use think\Model;
use donatj\UserAgentParser;

/**
 * @mixin think\Model
 */
class UserLog extends Model
{
    //

    public function user()
    {
        return $this->belongsTo(User::class, 'user_id')
            ->bind(['username'])
            ;
    }

    public function role()
    {
        return $this->belongsTo(Role::class, 'role_id')
            ->bind(['role_name' => 'name'])
            ;
    }

    public function getMethodAttr($val)
    {
        $arr = [1=>'企业微信扫码', 2=>'正常登录'];
        if (!in_array($val, array_keys($arr))) {
            return '未知';
        }
        return $arr[$val];
    }

    public function getHandleAttr($val)
    {
        $arr = [1=>'登入', 2=>'登出', 3=>'超时'];
        if (!in_array($val, array_keys($arr))) {
            return '未知';
        }
        return $arr[$val];
    }

    /**
     * 写入追踪记录
     * 
     * @param int $h 操作 1=登入(默认), 2=登出
     * @param int $t 类型 1=扫码(默认), 2=普通
     */
    public function write($h=1, $t=1)
    {
        $location = location();
        $ua_str = $_SERVER['HTTP_USER_AGENT'];
        $ua = parse_user_agent();
        $t = $h == 1 ? $t : 0;
        $user_id = empty(session('uid')) ? 0 : session('uid');
        $role_id = empty(session('info.role_id')) ? 0 : session('info.role_id');
        $data = [
            'user_id' => $user_id,
            'role_id' => $role_id,
            'method' => intval($t),
            'handle' => intval($h),
            'client_ip' => request()->ip(),
            'url' => request()->url(),
            'position' => empty($location['addr']) ? '获取失败' : $location['addr'],
            'user_agent' => $ua_str,
            'from' => sprintf('平台: %s / 浏览器: %s %s', $ua['platform'], $ua['browser'], $ua['version']),
        ];

        return $this->save($data);
    }

}
